package com.yuyou.train.admin.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.yuyou.train.admin.mapper.AuthUserMapper;
import com.yuyou.train.admin.service.IAuthUserRoleRelationService;
import com.yuyou.train.admin.service.IAuthUserService;
import com.yuyou.train.admin.service.ICommDataConfigService;
import com.yuyou.train.admin.vo.req.ReqAuthUserAdd;
import com.yuyou.train.admin.vo.req.ReqAuthUserUpdate;
import com.yuyou.train.service.api.admin.dto.AuthUserDTO;
import com.yuyou.train.service.api.admin.entity.AuthUser;
import com.yuyou.train.service.api.admin.entity.AuthUserRoleRelation;
import com.yuyou.train.service.api.admin.entity.CommDataConfig;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.enums.admin.AuthUserEnums;
import com.yuyou.train.util.enums.admin.CommDataConfigEnums;
import com.yuyou.train.util.message.admin.AuthUserMess;
import com.yuyou.train.util.tool.BeanUtils;
import com.yuyou.train.util.tool.DateUtil;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.Sequence;
import com.yuyou.train.util.tool.UUIDUtil;

/**
 * Created by yujin.liu on 2018/1/19.
 */
@Service
public class AuthUserServiceImpl implements IAuthUserService{

    @Autowired
    private AuthUserMapper authUserMapper;

    @Autowired
    private IAuthUserRoleRelationService authUserRoleRelationService;

    @Autowired
    private ICommDataConfigService commDataConfigService;

    @Override
    public AuthUserDTO findAuthUser(String id){
        AuthUserDTO authUserDTO = authUserMapper.selectByPrimaryKey(id);

        authUserDTO.setAreaName(getAreaNameByAreaIds(authUserDTO.getAreaId()));
        return authUserDTO;
    }



    @Override
    @Transactional(timeout=60)
    public ResBoolSimpleInfo insertAuthUser(ReqAuthUserAdd reqAuthUserAdd){


        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(reqAuthUserAdd, authUser);

        ResBoolSimpleInfo res = new ResBoolSimpleInfo();
        AuthUser authUserQuery = seleteAuthUserByAccount(authUser.getAccount());
        if(null != authUserQuery){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }

        authUser.setId(Sequence.getSequence().getNextId());
        authUser.setStatus(AuthUserEnums.status.normal.getValue());
        authUser.setCreateTime(DateUtil.now());
        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.insert(authUser);

        // 添加角色关系
        AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
        authUserRoleRelation.setId(Sequence.getSequence().getNextId());
        authUserRoleRelation.setAuthUserId(authUser.getId());
        authUserRoleRelation.setAuthRoleId(reqAuthUserAdd.getAuthRoleId());
        authUserRoleRelation.setCreateTime(DateUtil.now());
        authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);

        return ResBoolSimpleInfo.getSuccessInfo();
    }


    @Override
    public ResBoolSimpleInfo updateAuthUser(ReqAuthUserUpdate reqAuthUserUpdate){
        AuthUser authUser = new AuthUser();
        DefindBeanUtils.copyProperties(reqAuthUserUpdate, authUser);

        ResBoolSimpleInfo res = new ResBoolSimpleInfo();
        AuthUser authUserQuery = seleteAuthUserByAccount(authUser.getAccount());
        if(null != authUserQuery && !authUserQuery.getId().equals(authUser.getId())){
            res.setSuccess(false);
            res.setMessage(AuthUserMess.ACCOUNT_EXIST);
            return res;
        }
        authUser.setAccount(null); // 账号不能改
//        authUser.setStatus(authUserQuery.getStatus());
        authUser.setUpdateTime(DateUtil.now());
        authUserMapper.updateByPrimaryKeySelective(authUser);

        // 更新角色关系，先删除再插入
        authUserRoleRelationService.deleteByUserId(authUser.getId());

        AuthUserRoleRelation authUserRoleRelation = new AuthUserRoleRelation();
        authUserRoleRelation.setId(Sequence.getSequence().getNextId());
        authUserRoleRelation.setAuthUserId(authUser.getId());
        authUserRoleRelation.setAuthRoleId(reqAuthUserUpdate.getAuthRoleId());
        authUserRoleRelation.setCreateTime(DateUtil.now());
        authUserRoleRelationService.insertAuthUserRoleRelation(authUserRoleRelation);

        return ResBoolSimpleInfo.getSuccessInfo();
    }


    @Override
    public int updateByPrimaryKeySelective(AuthUser authUser) {
        authUser.setUpdateTime(DateUtil.now());
        return authUserMapper.updateByPrimaryKeySelective(authUser);
    }

    @Override
    public int deleteAuthUserById(String id) {
        return authUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int findAuthUserPageCount(Pagination<AuthUserDTO> p) {
        return authUserMapper.findAuthUserPageCount(p);
    }

    @Override
    public List<AuthUserDTO> findAuthUserPageList(Pagination<AuthUserDTO> p) {
        List<AuthUserDTO> authUserPageList = authUserMapper.findAuthUserPageList(p);
        for(AuthUserDTO authUserDTO : authUserPageList){
            authUserDTO.setAreaName(getAreaNameByAreaIds(authUserDTO.getAreaId()));
        }

        return authUserPageList;
    }

	@Override
	public AuthUser seleteAuthUserByAccount(String account) {
		return authUserMapper.seleteAuthUserByAccount(account);
	}


	@Override
	public AuthUser selectBaseByPrimaryKey(String id) {
		return authUserMapper.selectBaseByPrimaryKey(id);
	}

    private String getAreaNameByAreaIds(String areaIdsStr){
        List<CommDataConfig> areaList = commDataConfigService.findUseByCategory(CommDataConfigEnums.category.area.getValue());
        Map<Object, CommDataConfig> areaMap = BeanUtils.toMap(areaList, "id");

        List<String> areaIds = Arrays.asList(areaIdsStr.split(","));

        String areaName = "";
        for(String areaId : areaIds){
            if(StringUtils.isEmpty(areaName)){
                areaName += areaMap.get(areaId).getName();
            }else {
                areaName = areaName + "," + areaMap.get(areaId).getName();
            }
        }
        return areaName;
    }



}
